<?php

namespace app\common\model\xiluedu;

use app\common\library\Auth;
use app\common\model\User;
use think\Db;
use think\Exception;
use think\Hook;
use think\Model;
use function fast\array_get;


class CourseOrder extends Model
{
    // 表名
    protected $name = 'xiluedu_course_order';

    protected $autoWriteTimestamp = 'int';

    protected $createTime = 'createtime';
    protected $updateTime = 'updatetime';
    protected $deleteTime = false;

    public function user() {
        return $this->belongsTo(User::class, 'user_id')->setEagerlyType(0);
    }

    public function course() {
        return $this->belongsTo('Course', 'course_id')->setEagerlyType(0);
    }

    public static function lists($params,$user_id){

        $tab = array_get($params,'tab');
        $pagesize = array_get($params,'pagesize',10);
        $where['user_id'] = $user_id;
        if($tab == 1){
            $where['pay_status'] = 1;
        }else if($tab == 2){
            $where['pay_status'] = 2;
        }
        return self::where($where)
            ->with(['course'=>function($query){
                $query->withField(['id','type','name','category_id','teacher_id','thumb_image','description','collection_count','salesprice']);
            }])
            ->order('updatetime desc')
            ->paginate($pagesize);
    }

    public static function detail($order_id){

        return self::where('course_order.id',$order_id)
            ->with(['course'=>function($query){
                $query->withField(['id','type','name','category_id','teacher_id','thumb_image','description','collection_count','salesprice']);
            }])
            ->find();
    }


    //确认下单
    public static function sure($params){
        if($course_id = array_get($params,'course_id')){
            $row = Course::with(['teacher'=>function($query){
                $query->withField(['id','name','job']);
            }])->field('id,name,status,salesprice,teacher_id,thumb_image')->where('id',$course_id)->find();
            if(!$row || $row->status == 0){
                throw new Exception("课程不存在或已下架");
            }
            $total_price = $row->salesprice;
            $pay_price = $row->salesprice;
            $user_coupon_id = array_get($params,'user_coupon_id');
            //优惠券
            $coupons = UserCoupon::getCanCoupon($course_id);
            $coupon_price = 0;
            $can_coupon = [];
            $use_coupon = [];
            foreach ($coupons as $coupon){
                if($coupon['range_status'] == '1'){
                    if($pay_price >= $coupon['at_least']){
                        if(!$user_coupon_id || $user_coupon_id == $coupon['user_coupon_id']){
                            list($coupon_price,$use_coupon) = self::coupon_cal($coupon,$pay_price,$coupon_price,$use_coupon);
                        }
                        $can_coupon[] = $coupon;
                        continue;
                    }
                }
                else{
                    #课程id
                    if($row['salesprice'] >= $coupon['at_least']){
                        if(!$user_coupon_id || $user_coupon_id == $coupon['user_coupon_id']){
                            list($coupon_price,$use_coupon) = self::coupon_cal($coupon,$row['salesprice'],$coupon_price,$use_coupon);
                        }
                        $can_coupon[] = $coupon;
                        break;
                    }
                }
            }
            unset($coupon);
            //修正大于价格的优惠券
            if($pay_price < $coupon_price){
                $coupon_price = 0;
                $use_coupon = [];
            }

            foreach ($can_coupon as $coupon){
                $coupon['checked'] = false;
                if($coupon['id'] == $use_coupon['id']){
                    $coupon['checked'] = true;
                }
            }

            $pay_price = $pay_price - $coupon_price;

            $orderinfo = [
                'pay_price'     => $pay_price,
                'total_price'   => $total_price,
                'course'        => $row,
                'coupon_price'  =>  $coupon_price,
                'use_coupon'   =>  $use_coupon,
                'available_coupon'=>$can_coupon,
            ];
            return $orderinfo;
        }else{
            throw new Exception("非法参数");
        }
    }


    protected static function coupon_cal($coupon,$price,$coupon_price,$use_coupon){

        if($coupon['type'] == '1'){
            if($coupon_price < $coupon['money']){
                $coupon_price = $coupon['money'];
                $use_coupon = [
                    'id'=>$coupon['id'],'name'=>$coupon['name'],
                    'type'=>$coupon['type'],'discount'=>$coupon['discount'],
                    'at_least'=>$coupon['at_least'],'money'=>$coupon['money'],
                    'range_status'=>$coupon['range_status'],'user_coupon_id'=>$coupon['user_coupon_id'],
                ];
            }
        }
        else{
            //$discount_price = sprintf('%.2f',(100-$coupon['discount']) / 100 * $price) ;
            $discount_price = bcmul(bcdiv(bcsub(100,$coupon['discount']),100,2),$price,2);
            if($coupon_price < $discount_price){
                $coupon_price = $discount_price;
                $use_coupon = [
                    'id'=>$coupon['id'],'name'=>$coupon['name'],
                    'type'=>$coupon['type'],'discount'=>$coupon['discount'],
                    'at_least'=>$coupon['at_least'],'money'=>$coupon['money'],
                    'range_status'=>$coupon['range_status'],'user_coupon_id'=>$coupon['user_coupon_id'],
                ];
            }
        }
        return [$coupon_price,$use_coupon];
    }

    public static function createOrder($params) {
        $sure = static::sure($params);
        $auth = Auth::instance();
        if(UserCourse::isBuy($auth->id,$params['course_id'])){
            throw new  Exception("无需重复购买课程");
        }
        db()->startTrans();
        #订单创建
        $data = [
            'platform'      =>  array_get($params,'platform','wxmin'),
            'user_id'       =>  $auth->id,
            'order_no'      =>  "C".date("YmdHis").mt_rand(10,9999),
            'course_id'     =>  $sure['course']['id'],
            'total_price'   =>  $sure['total_price'],
            'pay_price'     =>  $sure['pay_price'],
            'user_coupon_id'=>  $sure['use_coupon']['user_coupon_id'] ?? 0,
            'favourable_price'=>  $sure['coupon_price'],
            'ip'            => request()->ip(),
            'pay_status'    =>  1
        ];
        try {
            $result = self::create($data);
            $result2 = true;
            if($sure['use_coupon']){
                $result2 = UserCoupon::where('id',$sure['use_coupon']['user_coupon_id'])->update(['use_status'=>1,'usetime'=>time()]);
            }
        }catch (Exception $e){
            throw $e;
        }
        if($result2 && $result !== false){
            db()->commit();
            return $result;
        }else {
            db()->rollback();
            throw new Exception("订单创建失败");
        }
    }

    public static function pay_notify($order_no,$transation_id=''){
        $order = self::where('order_trade_no',$order_no)->find();
        if(!$order){
            throw new Exception('订单不存在');
        }
        if($order->pay_status == '2'){
            throw new Exception('订单已支付完毕');
        }
        $order->pay_status = '2';
        $order->paytime = time();
        $order->save();
        Course::where('id',$order->course_id)->setInc('real_num',1);
        $user_course = [
            'user_id'   =>  $order->user_id,
            'course_id' =>  $order->course_id,
        ];
        UserCourse::create($user_course);
        Hook::listen("xiluedu_course_buy",$order);
        return $order;
    }

}
